package org.jeecg.modules.monitoring.j_monitoring.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

import com.alibaba.fastjson.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xkcoding.http.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.monitoring.j_monitoring.entity.EndpointVO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class HuaweiOpt {
    // 所有请求的地址
    private final String host = "10.57.2.250:8443";
    private final String oragin = "https://" + host;
    private final String loginPage = oragin + "/OPMUI/jsp/secospace/login.jsp";
    private final String loginUrl = oragin + "/OPMUI/business/tsmLogin!login.action";
    private final String loginHeart = oragin + "/OPMUI/business/tsmLogin!sessionHeartbeat.action";
    private final String getEndpointUrl = oragin + "/OPMUI/secospace/endPointAction!getEndPointsByGroupId.action";
    private final String addEndpointUrl = oragin + "/OPMUI/secospace/endPointAction!saveEndPoints.action";
    private final String updateEndpointUrl = oragin + "/OPMUI/secospace/endPointAction!updateEndPoints.action";
    private final String deleteEndpointUrl = oragin + "/OPMUI/secospace/endPointAction!deleteEndPoints.action";

    // 请求用到的cookie信息
    private List<HttpCookie> cookies = new ArrayList<HttpCookie>();
    // 请求用到的xsrf信息，跨站请求使用, 可能没用
    private String xsrfToken = "";
    String cookieStr = "";
    // 请求用到的header信息
    private Map<String, String> headers = new HashMap<String, String>();

    // 默认账号信息
    private String defUserName = "admin", defPassword = "Huawei@123";

    /**
     * 执行登录操作
     */
    private boolean login() {
        log.error("【login】start");
        String username = defUserName, password = defPassword;
        // 获取登录界面中的hashcode值
        HttpResponse loginHtmlResp = HttpRequest.get(loginPage)
                .timeout(20000).execute();
        Document loginDoc = Jsoup.parse(loginHtmlResp.body());
        Element hashEl = loginDoc.getElementById("hashcode");
        String hashcode = hashEl.attr("value");
        log.error("【login】hashcode: {}", hashcode);

        // 登录参数
        Map<String, Object> loginParams = new HashMap<String, Object>();
        loginParams.put("userName", username);
        loginParams.put("password", password);
        loginParams.put("hashcode", hashcode);
        loginParams.put("validCode", "");

        // 登录请求执行
        HttpResponse loginResp = HttpRequest.post(loginUrl).setFollowRedirectsCookie(true)
                .form(loginParams)
                .timeout(20000).execute();
        String loginResultStr = loginResp.body();
        log.error("【login】result: {}", loginResultStr);

        JSONObject loginResult = JSONObject.parseObject(loginResultStr);
        xsrfToken = loginResult.getString("data");

        // 登录信息记录到cookie和header中，以便遍后续调用使用
        HttpCookie xsrfCookie = new HttpCookie("XSRF-TOKEN", xsrfToken);
        xsrfCookie.setPath("/");
        xsrfCookie.setSecure(true);

        // 获取cookie
        cookies = loginResp.getCookies();
        cookies.add(xsrfCookie);
        createAddHeaders();
        return true;
    }

    private void createAddHeaders() {
        cookieStr = "";
        for (int i = 0; i < cookies.size(); i++) {
            HttpCookie cookieTemp = cookies.get(i);
            cookieStr += cookieTemp.getName() + "=" + cookieTemp.getValue() + "; ";
        }
        cookieStr = cookieStr.substring(0, cookieStr.length() - 2);
        headers.put(Header.COOKIE.getValue(), cookieStr);
        headers.put("X-XSRF-TOKEN", xsrfToken);
        headers.put(Header.ORIGIN.getValue(), oragin);
        headers.put(Header.HOST.getValue(), host);
    }

    /**
     * 校验是否过期，如果过去则直接执行登录,执行运行
     */
    public boolean checkLogin() {
        log.error("【checkLogin】start");
        if (StrUtil.isEmpty(xsrfToken)) {
            login();
            return true;
        }
        log.error("【checkLogin】start");

        HttpResponse resp = HttpRequest.post(loginHeart)
                .setFollowRedirectsCookie(true).cookie(cookies)
                .addHeaders(headers).keepAlive(true)
                .timeout(20000).execute();
        String resultStr = resp.body();
        if (StringUtil.isEmpty(resultStr)){
            xsrfToken = "";
            login();
            return true;
        }
        log.error("【checkLogin】result: {}", resultStr);
        JSONObject loginHeartResult = JSONObject.parseObject(resultStr);
        String message = loginHeartResult.getString("message");
        log.error("【checkLogin】end");
        if ("session time out".equals(message)) {
            xsrfToken = "";
            login();
            return true;
        } else {
            return true;
        }
    }

    /**
     * 添加mac信息
     */
    public boolean addEndpoint(EndpointVO endpointVO) {
        log.error("【addEndpoint】start: {}", endpointVO.getMac());
        log.error("【addEndpoint】add Args: {}", JSONUtil.toJsonStr(endpointVO.toAddMap()));
        HttpRequest req = HttpRequest.post(addEndpointUrl)
                .setFollowRedirectsCookie(true).cookie(cookies)
                .addHeaders(headers).keepAlive(true).form(endpointVO.toAddMap());
        HttpResponse resp = req.timeout(20000).execute();

        String resultStr = resp.body();
        log.error("【addEndpoint】result: {}", resultStr);
        JSONObject result = JSONObject.parseObject(resultStr);
        Boolean success = result.getBoolean("success");
        log.error("【addEndpoint】end: {}", endpointVO.getMac());
        return success;
    }

    /**
     * 获取终端信息
     *
     * @param mac
     * @return
     */
    public JSONObject getPageList(Integer pageNo,Integer pageSize,String node, String mac,String deviceType,String ip) {
        log.error("【getEndpoint】start: {}", mac);
        // 查询参数
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("start", (pageNo-1)*pageSize);
        params.put("limit", pageSize);
        params.put("node", node);
        params.put("deviceType", deviceType);
        params.put("ip", ip);
        params.put("searchType", "endpoint");
        params.put("mac", mac);
        params.put("addPageNo", 0);
        params.put("deployState", -1);

        // 执行查询
        HttpRequest req = HttpRequest.post(getEndpointUrl)
                .setFollowRedirectsCookie(true).cookie(cookies)
                .addHeaders(headers).keepAlive(true).form(params);
        HttpResponse resp = req.timeout(20000).execute();

        String resultStr = resp.body();

        resultStr = resultStr.replaceAll("&quot;","\"");
        log.error("【getEndpoint】result: {}", resultStr);
        System.out.println(resultStr);

        JSONObject result = com.alibaba.fastjson.JSONObject.parseObject(resultStr);
//        Boolean success = result.getBool("success");
//        Integer total = result.getInt("total");
//        if (success && total >= 1) {
//            JSONObject data = result.getJSONArray("data").getJSONObject(0);
//            EndpointVO endpointVO = new EndpointVO();
//            endpointVO.setId(data.getStr("id"));
//            endpointVO.setMac(data.getStr("mac"));
//            endpointVO.setHostName(data.getStr("hostName"));
//            endpointVO.setDeviceType(data.getStr("deviceType"));
//            endpointVO.setDescription(data.getStr("description"));
//
//            log.error("【getEndpoint】end: {}", mac);
//        }
//
//        log.error("【getEndpoint】end: {}", mac);

        return result;
    }

    /**
     * 获取终端信息
     *
     * @param mac
     * @return
     */
    public JSONObject getOne(String node, String mac) {
        log.error("【getEndpoint】start: {}", mac);
        // 查询参数
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("start", 0);
        params.put("limit", 20);
        params.put("node", node);
        params.put("searchType", "endpoint");
        params.put("mac", mac);
        params.put("addPageNo", 0);
        params.put("deployState", -1);

        // 执行查询
        HttpRequest req = HttpRequest.post(getEndpointUrl)
                .setFollowRedirectsCookie(true).cookie(cookies)
                .addHeaders(headers).keepAlive(true).form(params);
        HttpResponse resp = req.timeout(20000).execute();

        String resultStr = resp.body();
        log.error("【getEndpoint】result: {}", resultStr);
        JSONObject result = JSONObject.parseObject(resultStr);
        Boolean success = result.getBoolean("success");
        Integer total = result.getInteger("total");
        if (success && total >= 1) {
            JSONObject data = result.getJSONArray("data").getJSONObject(0);
            return data;
        }

        log.error("【getEndpoint】end: {}", mac);
        return null;
    }

    /**
     * 获取终端信息
     *
     * @param mac
     * @return
     */
    private EndpointVO getEndpoint(String node, String mac) {
        log.error("【getEndpoint】start: {}", mac);
        // 查询参数
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("start", 0);
        params.put("limit", 20);
        params.put("node", node);
        params.put("searchType", "endpoint");
        params.put("mac", mac);
        params.put("addPageNo", 0);
        params.put("deployState", -1);

        // 执行查询
        HttpRequest req = HttpRequest.post(getEndpointUrl)
                .setFollowRedirectsCookie(true).cookie(cookies)
                .addHeaders(headers).keepAlive(true).form(params);
        HttpResponse resp = req.timeout(20000).execute();

        String resultStr = resp.body();
        log.error("【getEndpoint】result: {}", resultStr);
        JSONObject result = JSONObject.parseObject(resultStr);
        Boolean success = result.getBoolean("success");
        Integer total = result.getInteger("total");
        if (success && total >= 1) {
            JSONObject data = result.getJSONArray("data").getJSONObject(0);
            EndpointVO endpointVO = new EndpointVO();
            endpointVO.setId(data.getString("id"));
            endpointVO.setMac(data.getString("mac"));
            endpointVO.setHostName(data.getString("hostName"));
            endpointVO.setDescription(data.getString("description"));

            log.error("【getEndpoint】end:  {}", JSONUtil.toJsonStr(endpointVO));
            return endpointVO;
        }

        log.error("【getEndpoint】end: {}", mac);
        return null;
    }

    /**
     * 删除终端信息
     */
    public boolean batchDeleteEndpoint(String ids, Integer groupId, String macs) {
        log.error("【delEndpoint】start: {}", macs);
        // 获取需要删除的终端信息
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("ids", ids);
        params.put("groupId", groupId);
        params.put("macs", macs);
        params.put("alsoDeleteDeployInfo", true);
        // 删除执行
        HttpRequest req = HttpRequest.post(deleteEndpointUrl)
                .setFollowRedirectsCookie(true).cookie(cookies)
                .addHeaders(headers).keepAlive(true).form(params);
        HttpResponse resp = req.timeout(20000).execute();

        String resultStr = resp.body();
        log.error("【delEndpoint】result: {}", resultStr);
        JSONObject result = JSONObject.parseObject(resultStr);
        Boolean success = result.getBoolean("success");
        log.error("【delEndpoint】end: {}", macs);
        return success;
    }

    /**
     * 删除终端信息
     */
    public boolean delEndpoint(String node, Integer groupId, String mac) {
        log.error("【delEndpoint】start: {}", mac);
        // 获取需要删除的终端信息
        EndpointVO endpointVO = getEndpoint(node, mac);
        // 删除参数
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("ids", endpointVO.getId());
        params.put("groupId", groupId);
        params.put("macs", mac);
        params.put("alsoDeleteDeployInfo", true);
        // 删除执行
        HttpRequest req = HttpRequest.post(deleteEndpointUrl)
                .setFollowRedirectsCookie(true).cookie(cookies)
                .addHeaders(headers).keepAlive(true).form(params);
        HttpResponse resp = req.timeout(20000).execute();

        String resultStr = resp.body();
        log.error("【delEndpoint】result: {}", resultStr);
        JSONObject result = JSONObject.parseObject(resultStr);
        Boolean success = result.getBoolean("success");
        log.error("【delEndpoint】end: {}", endpointVO.getMac());
        return success;
    }

    /**
     * 更新终端信息
     */
    public boolean updateEndpoint(EndpointVO endpointVO) {
        log.error("【updateEndpoint】start: {}", endpointVO.getMac());
        // 获取需要修改的终端Id
        EndpointVO endpointtemp = getEndpoint(endpointVO.getNode(), endpointVO.getMac());
        endpointVO.setId(endpointtemp.getId());
        // 进行更新操作
        HttpRequest req = HttpRequest.post(updateEndpointUrl)
                .setFollowRedirectsCookie(true).cookie(cookies)
                .addHeaders(headers).keepAlive(true).form(endpointVO.toUpdateMap());
        HttpResponse resp = req.timeout(20000).execute();

        String resultStr = resp.body();
        log.error("【updateEndpoint】result: {}", resultStr);
        JSONObject result = JSONObject.parseObject(resultStr);
        Boolean success = result.getBoolean("success");
        log.error("【updateEndpoint】end: {}", endpointVO.getMac());
        return success;
    }
}

